<template>
  <div class="login">
    <el-form ref="form" :rules="rules" :model="form" label-width="100px" class="form">
      <span class="title">账户登录</span>
      <el-form-item label="用户名" prop="username">
        <el-input placeholder="请输入您的用户名" v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" placeholder="请输入您的密码" v-model="form.password"></el-input>
      </el-form-item>
      <div style="text-align: center;">{{msg}}</div>
      <el-form-item>
        <el-button class="login-button" type="primary" @click="submit()">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 3, max: 15, message: '用户名3-15位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 18, message: '密码6-16位', trigger: 'blur' }
        ]
      },
      msg: ''
    }
  },
  methods: {
    submit () {
      this.$refs.form.validate((vali, obj) => {
        if (vali) {
          this.$http.post('users/login', JSON.stringify(this.form)).then((res) => {
            if (res.status === 200) {
              console.log(res)
              const userInfo = res.data
              userInfo.password = this.form.password
              this.$cookie.set('userInfo', JSON.stringify(userInfo))
              this.$cookie.set(res.data.tokenName, res.data.tokenValue)
              this.$router.push('/')
            }
          }).catch((err) => {
            if (err.response) {
              this.msg = err.response.data.message
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.login {
  width: 100%;
  height: 80%;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgb(226, 158, 133);
  .form {
    width: 30%;
    height: 50%;
    margin: 80px auto;
    background-color: aliceblue;
    padding: 30px;
    border-radius: 20px;
    .title {
      color: #303133;
      display: inline-block;
      text-align: center;
      width: 100%;
      height: 60px;
      font-size: 20px;
      line-height: 63px;
    }
    .login-button {
      float: right;
      margin: 20px 0;
      background-color: #f40;
      border: #f40;
      &:hover {
      background-color: rgb(253, 165, 132);
      border: rgb(253, 165, 132);
      }
    }
  }
}
</style>
